package img

import (
	"bytes"
	"encoding/base64"
	"github.com/nfnt/resize"
	"github.com/skip2/go-qrcode"
	"image"
	"image/draw"
	"image/jpeg"
	"io"
	"net/http"
)

func BaseImgToQrcode(content string) (string, error) {
	imgByte, err := qrcode.Encode(content, qrcode.High, 256)
	if err != nil {
		return "", err
	}

	mimeType := http.DetectContentType(imgByte)
	var baseImg string
	switch mimeType {
	case "image/jpeg":
		baseImg = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(imgByte)
	case "image/png":
		baseImg = "data:image/png;base64," + base64.StdEncoding.EncodeToString(imgByte)
	}
	return baseImg, nil
}

// CreateQrCodeWithLogo 带logo的二维码图片生成 content-二维码内容   level-容错级别,Low,Medium,High,Highest   size-像素单位
func CreateQrCodeWithLogo(content string, logoReader io.Reader, level qrcode.RecoveryLevel, size int) []byte {
	code, err := qrcode.New(content, level)
	if err != nil {
		return nil
	}
	code.DisableBorder = true
	// 设置文件大小并创建画板
	qrcodeImg := code.Image(size)
	outImg := image.NewRGBA(qrcodeImg.Bounds())
	logoImg, _, err := image.Decode(logoReader)
	logoImg = resize.Resize(uint(size/6), uint(size/6), logoImg, resize.Lanczos3)
	//logo和二维码拼接
	draw.Draw(outImg, outImg.Bounds(), qrcodeImg, image.Pt(0, 0), draw.Over)
	offset := image.Pt((outImg.Bounds().Max.X-logoImg.Bounds().Max.X)/2, (outImg.Bounds().Max.Y-logoImg.Bounds().Max.Y)/2)
	draw.Draw(outImg, outImg.Bounds().Add(offset), logoImg, image.Pt(0, 0), draw.Over)

	buf := new(bytes.Buffer)
	jpeg.Encode(buf, outImg, nil)
	return buf.Bytes()
}

func BaseImgToQrcodeWithLog(content string, logoReader io.Reader, size int) (string, error) {
	imgByte := CreateQrCodeWithLogo(content, logoReader, qrcode.Highest, size)
	mimeType := http.DetectContentType(imgByte)
	var baseImg string
	switch mimeType {
	case "image/jpeg":
		baseImg = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(imgByte)
	case "image/png":
		baseImg = "data:image/png;base64," + base64.StdEncoding.EncodeToString(imgByte)
	}
	return baseImg, nil
}
